﻿using System; 
using System.Collections.ObjectModel; 

namespace ICSharpCode.WinFormsUI.Controls
{
    #region NodeCollection

    public class NodeCollection : Collection<Node>
    {
        private Node _owner;

        public NodeCollection(Node owner)
        {
            _owner = owner;
        }

        protected override void ClearItems()
        {
            while (this.Count != 0)
                this.RemoveAt(this.Count - 1);
        }

        protected override void InsertItem(int index, Node item)
        {
            if (item == null)
                throw new ArgumentNullException("item");

            if (item.Parent != _owner)
            {
                if (item.Parent != null)
                    item.Parent.Nodes.Remove(item);
                item._parent = _owner;
                base.InsertItem(index, item);

                NTreeViewModel model = _owner.FindModel();
                if (model != null)
                    model.OnNodeInserted(_owner, index, item);
            }
        }

        protected override void RemoveItem(int index)
        {
            Node item = this[index];
            item._parent = null;
            base.RemoveItem(index);

            NTreeViewModel model = _owner.FindModel();
            if (model != null)
                model.OnNodeRemoved(_owner, index, item);
        }

        protected override void SetItem(int index, Node item)
        {
            if (item == null)
                throw new ArgumentNullException("item");

            RemoveAt(index);
            InsertItem(index, item);
        }
    }

    #endregion
}
